<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission as PermissionModel;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if( !Auth::guard('admin')->check()){
            echo '<script>window.parent.location.href="/admin/login";</script>';
            exit;
            //return redirect('/admin/login');
        }
        $id = Auth::guard('admin')->id();
        $user = \App\models\adminer::findorfail($id);
        $path = $request->path();
        $routeName = $request->route()->getName();
        if( !($user->hasAnyRole('超级管理员') || $user->hasAnyRole(1))  && $path != 'admin/index'  ){
            $per = PermissionModel::where('rule',"/$path")
                ->when($routeName,function($query) use ($routeName){
                    $query->orWhereRaw('FIND_IN_SET(?,rule)',[$routeName]);
                })
                ->first();
            if( !$per || !$user->hasPermissionTo($per->id) ){
                if(strstr($path,'delete') || strstr($path,'destroy') || strstr($path,'upstatus')){
                    return response()->json(['code'=>0,'msg' => '操作失败,没有操作权限']);   exit();
                };
                if($request->ajax()){
                    return response()->json([
                        'code'      => 0,
                        'message'   => '没有操作权限',
                        'data'      => '',
                        'redirect'  => 'parent'
                    ]);
                }else{
                    return redirect()->route('error');
                }
            }
        }
        return $next($request);
    }
}
